using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Content.PM;
using Android.Provider;
using Java.IO;

namespace TMM
{
    public class CameraHelper
    {
        MainActivity mainActivity = null;
        Java.IO.File _dir;
        int photoRequestCode;

        public CameraHelper(MainActivity activity)
        {
            mainActivity = activity;
        }

        public void CapturePicture(int requestCode)
        {
            photoRequestCode = requestCode;
            if (!IsThereAnAppToTakePictures())
            {
                Toast.MakeText(mainActivity, "Nu aveti nicio aplicatie instalata care poate face poze.", ToastLength.Short);
                return;
            }

            CreateDirectoryForPictures();
            TakePicture();
        }

        public void GetPictureFromLocalStorage(int requestCode)
        {
            Intent intent = new Intent();
            intent.SetType("image/*");
            intent.SetAction(Intent.ActionGetContent);
            intent.AddCategory(Intent.CategoryOpenable);
            mainActivity.StartActivityForResult(Intent.CreateChooser(intent, "Complete action using"), requestCode);
        }

        private bool IsThereAnAppToTakePictures()
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);
            IList<ResolveInfo> availableActivities = mainActivity.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
            return availableActivities != null && availableActivities.Count > 0;
        }

        private void CreateDirectoryForPictures()
        {
            _dir = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "TMM");
            if (!_dir.Exists())
                _dir.Mkdirs();
        }

        private void TakePicture()
        {
            Intent intent = new Intent(MediaStore.ActionImageCapture);
            mainActivity.StartActivityForResult(intent, photoRequestCode);
        }
    }
}